// 引入electron并创建一个Browserwindow
const { app, BrowserWindow, ipcMain, Menu, MenuItem } = require('electron')
const path = require('path')
const url = require('url')
const { WINDOW_CONFIG } = require('./config')

class WindowManager {
  constructor() {
    this.windowMap = new Map()
  }

  createLoginWindow() {
    let config = { ...WINDOW_CONFIG.LOGIN_WINDOW }
    if (process.platform === 'darwin') {
      config.titleBarStyle = 'default'
    }
    const loginWindow = new BrowserWindow(config)
    if (process.env.NODE_ENV) {
      loginWindow.openDevTools({ mode: 'detach' })
    }
    loginWindow.loadURL(
      'file://' + path.join(__dirname, './src/login/index.html')
    )
    this.windowMap.set('login', loginWindow)
  }

  closeLoginWindow() {
    const loginWindow = this.windowMap.get('login')
    loginWindow && loginWindow.close()
  }

  createMainWindow() {
    let config = { ...WINDOW_CONFIG.MAIN_WINDOW }
    //hack macOS config
    if (process.platform === 'darwin') {
      config.titleBarStyle = 'default'
    }
    const mainWindow = new BrowserWindow(config)
    mainWindow.once('ready-to-show', () => {
      // mainWindow.hide()
    })
    //拦截关闭 处理是最小化到托盘还是关闭
    /* mainWindow.once('close', evt => {
      evt.preventDefault()
      mainWindow.hide()
      evt.sender.send('save-config')
    }) */
    let loadUrl = `file://${path.join(__dirname, './build/index.html')}`
    if (process.env.NODE_ENV == 'development') {
      mainWindow.openDevTools({ mode: 'detach' })
      loadUrl = 'http://localhost:3000'
    }
    mainWindow.loadURL(loadUrl)
    mainWindow.on('closed', () => {
      this.windowMap.delete('main')
    })
    this.windowMap.set('main', mainWindow)
    this.createMainWindowMenu()

    // mainWindow.openDevTools({ mode: 'detach' })
  }

  createMainWindowMenu() {
    const mainWindowMenu = new Menu()
    const mainWindow = this.windowMap.get('main')
    mainWindowMenu.append(
      new MenuItem({
        label: '开发者工具',
        accelerator: 'CmdOrCtrl+I',
        click: (menuItem, browserWindow) => {
          browserWindow.openDevTools({ mode: 'detach' })
          browserWindow.send('open-devtools')
        }
      })
    )
    Menu.setApplicationMenu(mainWindowMenu)
  }

  closeMainWindow() {
    const mainWindow = this.windowMap.get('main')
    mainWindow && mainWindow.close()
  }

  hideMainWindow() {
    const mainWindow = this.windowMap.get('main')
    mainWindow && mainWindow.hide()
  }

  showMainWindow() {
    const mainWindow = this.windowMap.get('main')
    mainWindow && mainWindow.show()
  }

  get mainWindowExist() {
    return !!this.windowMap.get('main')
  }
}

class AppManager {
  constructor() {
    this.windowManager = new WindowManager()
    this._addListener()
  }

  _onAppActivate() {}

  _onMainMinimize() {
    const mainWindow = this.windowManager.windowMap.get('main')
    mainWindow.minimize()
  }

  _onMainMaximize() {
    const mainWindow = this.windowManager.windowMap.get('main')
    if (mainWindow.isMaximized()) {
      mainWindow.unmaximize()
    } else {
      mainWindow.maximize()
    }
  }

  _onMainClose() {
    const mainWindow = this.windowManager.windowMap.get('main')
    mainWindow.close()
  }

  _onMainLogout() {
    this.windowManager.hideMainWindow()
    this.windowManager.createLoginWindow()
  }

  _onLogin(args = ['login']) {
    const mainWindow = this.windowManager.windowMap.get('main')
    mainWindow.webContents.send('login', args[1])
    this.windowManager.closeLoginWindow()
    mainWindow.show()
  }

  _onLoginClose() {
    this.windowManager.closeLoginWindow()
    this.windowManager.closeMainWindow()
  }

  _addListener() {
    app.on('activate', this._onAppActivate)
    app.on('window-all-closed', () => {
      // macOS中除非用户按下 `Cmd + Q` 显式退出,否则应用与菜单栏始终处于活动状态.
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })
    ipcMain.on('application-message', (evt, ...args) => {
      if (args && args.length > 0) {
        switch (args[0]) {
          case 'main-minimize':
            this._onMainMinimize()
            break
          case 'main-maximize':
            this._onMainMaximize()
            break
          case 'main-close':
            this._onMainClose()
            break
          case 'main-logout':
            this._onMainLogout()
            break
          case 'login':
            this._onLogin(args)
            break
          case 'login-close':
            this._onLoginClose()
            break
          default:
            break
        }
      }
    })
  }

  _electronReady() {
    return new Promise(resolve => app.once('ready', resolve))
  }

  start() {
    this._electronReady().then(() => {
      // this.windowManager.createLoginWindow()
      this.windowManager.createMainWindow()
    })
  }
}
const appManager = new AppManager()
appManager.start()
